package com.meizi.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meizi.mall.product.dao.AttrAttrgroupRelationDao;
import com.meizi.mall.product.dao.AttrDao;
import com.meizi.mall.product.dao.AttrGroupDao;
import com.meizi.mall.product.dao.CategoryDao;
import com.meizi.mall.product.entity.AttrAttrgroupRelationEntity;
import com.meizi.mall.product.entity.AttrEntity;
import com.meizi.mall.product.entity.AttrGroupEntity;
import com.meizi.mall.product.entity.CategoryEntity;
import com.meizi.mall.product.service.AttrService;
import com.meizi.mall.product.service.CategoryService;
import com.meizi.mall.product.utils.ProjectQueryWapper;
import com.meizi.mall.product.vo.AttrVo;
import com.meizi.core.tool.api.PageUtils;
import com.meizi.core.tool.api.Query;
import com.meizi.core.tool.constant.ProductConstant;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, String attrType, Long categoryId) {
        ProjectQueryWapper<AttrEntity> attrEntityProjectQueryWapper = new ProjectQueryWapper<>();
        //1.查询Attr
        QueryWrapper<AttrEntity> queryWrapper =
                attrEntityProjectQueryWapper.productQueryAttrByCommon(params, attrType, categoryId, "attr_id", "attr_name");
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);

        //2.查询attrgroup,categroy
        List<AttrEntity> records = page.getRecords();
        List<AttrVo> listVos = new ArrayList<>();
        boolean isbase = "base".equalsIgnoreCase(attrType);
        if (records != null && records.size() > 0) {
            records.stream().forEach(attr -> {
                AttrVo attrVo = new AttrVo();
                BeanUtils.copyProperties(attr, attrVo);
                if (isbase) {
                    AttrAttrgroupRelationEntity attrgroupRelationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
                    if (attrgroupRelationEntity != null) {
                        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelationEntity.getAttrGroupId());
                        attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
                CategoryEntity categoryEntity = categoryDao.selectById(attr.getCatelogId());
                if (categoryEntity != null) {
                    attrVo.setCatelogName(categoryEntity.getName());
                }
                listVos.add(attrVo);
            });
        }
        pageUtils.setList(listVos);
        return pageUtils;
    }

    @Override
    public AttrVo getAttrInfo(Long attrId) {

        AttrEntity attr = getById(attrId);
        List<Long> paths = categoryService.findCatelogPath(attr.getCatelogId());
        AttrVo attrVo = new AttrVo();
        BeanUtils.copyProperties(attr, attrVo);
        attrVo.setCatelogPath(paths);

        if (ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()==attr.getAttrType()) {
            AttrAttrgroupRelationEntity attrgroupRelationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            attrVo.setAttrGroupId(attrgroupRelationEntity.getAttrGroupId());
        }

        return attrVo;
    }

    @Transactional()
    @Override
    public void updateVo(AttrVo vo) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(vo,attr);
        updateById(attr);
        if(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()==vo.getAttrType()){
            QueryWrapper<AttrAttrgroupRelationEntity> queryWrapper = new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId());
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(queryWrapper);
            if(vo.getAttrGroupId()==null){
                if(relationEntity!=null){
                    relationDao.delete(queryWrapper);
                }
                return;
            }

            if(relationEntity==null){
                relationEntity = new  AttrAttrgroupRelationEntity();
                relationEntity.setAttrId(attr.getAttrId());
                relationEntity.setAttrGroupId(vo.getAttrGroupId());
                relationDao.insert(relationEntity);
            }else if(!vo.getAttrGroupId().equals(relationEntity.getAttrGroupId())) {
                relationEntity.setAttrGroupId(vo.getAttrGroupId());
                relationDao.updateById(relationEntity);
            }
        }


    }

    /**
     * 根据分组id查找关联的所有基本属性
     * @param attrGroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {

        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));

        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if(attrIds == null || attrIds.size() == 0){
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public List<Long> selectCanSearchIds(List<Long> attrIds) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().in("attr_id", attrIds).eq("search_type", 1);
        List<AttrEntity> attrEntities = baseMapper.selectList(wrapper);
        return attrEntities.stream().map(AttrEntity::getAttrId).collect(Collectors.toList());

    }


}